import React, { useContext, useState, useEffect, useRef } from 'react';
import {
  message,
  Drawer,
  Form,
  Input,
  Button,
  Radio,
  InputNumber,
  Tabs,
  Table,
  Spin,
  Popconfirm,
} from 'antd';
import {
  upadataField,
  getMappingByTableid,
  getSqlDetail,
  createStructurebybaseTable,
  savaFile,
} from '../api';
import SetTask from './SetTask';

const { TabPane } = Tabs;

const UpdateForm = props => {
  // 结构化数据
  const { visible, onCancel, onSuccess, data, type, currentIndex = 0 } = props;

  // 初始化 form
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [listData, setListData] = useState([]); // 映射字段
  const [sqlData, setSqlData] = useState([]); //sql 语句

  const [itemId, setItemId] = useState();
  // 详情
  const getDetailData = () => {
    const paylaod = {
      id: data.id,
    };
    // setLoading(true);

    getMappingByTableid(paylaod).then(res => {
      setLoading(false);
      if (res.code === 0) {
        setItemId(res.data.id);
        const structure = res.data.structures || [];
        setListData(structure);
        // form.setFieldsValue({ ...res.data, ...data })
      } else {
        message.error(res.msg || '获取详情失败');
      }
    });
  };
  // 详情 sql
  const getSqlDetailData = () => {
    const paylaod = {
      id: data.id,
    };
    getSqlDetail(paylaod).then(res => {
      if (res.code === 0) {
        setSqlData(res.data);
        form.setFieldsValue({ ...res.data });
      } else {
        message.error(res.msg || '获取详情失败');
      }
    });
  };

  useEffect(() => {
    if (visible === true) {
      getDetailData();
      getSqlDetailData();
    } else {
      form.resetFields();
    }
  }, [visible]);

  // 栅格化
  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 18 },
  };

  /**
   * @en-US Update node
   * @zh-CN values
   *
   * @param fields
   */
  const updataData = values => {
    const hide = message.loading('正在请求数据');
    setLoading(true);

    const requirement = values.requirement ? ` where ${values.requirement}` : '';

    const paylaod = {
      comms: `select ${values.fields} from ${sqlData.tableName}${requirement}`,
      current: 1,
      pageSize: 10,
      firstcolumn: sqlData.firstcolumn,
      dataSourceId: sqlData.dataSourceId,
      pri: sqlData.pri,
      type: '1',
      dataUnitId: sqlData.dataUnitId,
    };
    upadataField(paylaod).then(res => {
      hide();
      setLoading(false);
      if (res.code === 0) {
        onCancel(false);
        onSuccess();
      } else {
        message.error(res.msg || '修改失败，请重试');
      }
    });
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param values
   */
  const sendData = () => {
    form.validateFields().then(values => {
      updataData(values);
    });
  };

  const modelClose = () => {
    onCancel(false);
  };

  // 页签切换
  const tabChange = () => {};

  //保存

  const save = () => {
    const payload = {
      id: data.id,
      structures: listData,
    };
    setLoading(true);
    savaFile(payload).then(res => {
      setLoading(false);
      if (res.code === 0) {
        message.success('保存成功！');
      } else {
        message.error(res.msg || '保存失败，请重试');
      }
    });
  };
  return (
    <>
      <Drawer
        getContainer={false}
        width={940}
        title={type === 'updata' ? '修改' : '添加'}
        visible={visible}
        onClose={modelClose}
        maskClosable={false}
        footer={
          <div
            style={{
              textAlign: 'right',
            }}
          >
            <Button onClick={modelClose} style={{ marginRight: 10 }}>
              取消
            </Button>
          </div>
        }
      >
        <Spin spinning={loading}>
          <div style={{ marginBottom: 10 }}>表名称：{data.tableName}</div>
          <Tabs onChange={tabChange} type="card">
            <TabPane tab="数据结构" key="1">
              {visible === true && <SetTask data={data} visible={visible} />}
            </TabPane>
            <TabPane tab="数据预览" key="2">
              <Form {...formItemLayout} name="control-ref" form={form}>
                <div style={{ marginBottom: 5 }}>select</div>
                <Form.Item label="" name="fields">
                  <Input.TextArea maxLength={1000} allowClear />
                </Form.Item>
                <div style={{ marginBottom: 5 }}>
                  from <span style={{ fontWeight: 'bold' }}>{sqlData.tableName}</span> where
                </div>
                <Form.Item label="" name="requirement">
                  <Input.TextArea maxLength={1000} allowClear />
                </Form.Item>
              </Form>
              <Button type="primary" onClick={sendData}>
                执行
              </Button>
            </TabPane>
          </Tabs>
        </Spin>
      </Drawer>
    </>
  );
};

export default UpdateForm;
